//
//  XMFeedbackFootView.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/5/22.
//

#import "XMFeedbackFootView.h"
#import "XMImgSelect.h"

@interface XMFeedbackFootView ()<UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UITextView *feedbackTextView;

@property (nonatomic, strong) UILabel *placeHolderLabel;
@property (nonatomic, strong) UILabel *wordNumLabel;

@property (nonatomic, strong) UIView *photoBgView;
@property (nonatomic, strong) UIButton *addImgBtn;

@property (nonatomic, strong) NSMutableArray *imgSelectArr;

@end

@implementation XMFeedbackFootView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    self.backgroundColor = kColorHEX(0xF7F7F7);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registerFirst:)];
    [self addGestureRecognizer:tap];
    
    UIView *feedbackView = [[UIView alloc] initWithFrame:CGRectMake(0, KScaleWidth(10.0), self.width, KScaleWidth(226.0))];
    feedbackView.backgroundColor = kColorHEX(0xffffff);
    [self addSubview:feedbackView];
    {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(22.0), KScaleWidth(15.0), feedbackView.width - KScaleWidth(22.0)*2, KScaleWidth(32.0)) font:KBoldFontSize(15.0) textColor:kColorHEX(0x333333)];
        titleLabel.text = @"请补充详细问题和意见";
        [feedbackView addSubview:titleLabel];
        
        UIView *textViewBgView = [[UIView alloc] initWithFrame:CGRectMake(KScaleWidth(20.0), titleLabel.maxY + KScaleWidth(10.0), feedbackView.width - KScaleWidth(20.0)*2, KScaleWidth(155.0))];
        textViewBgView.backgroundColor = kColorHEX(0xF6F6F6);
        [textViewBgView setCornerRadius:KScaleWidth(12.0)];
        [feedbackView addSubview:textViewBgView];
        
        UIImageView *writeIcon = [[UIImageView alloc] initWithFrame:CGRectMake(KScaleWidth(10.0), KScaleWidth(13.0), KScaleWidth(20.0), KScaleWidth(21.0))];
        writeIcon.contentMode = UIViewContentModeScaleAspectFit;
        writeIcon.image = ImageNamed(@"mine_write_icon");
        [textViewBgView addSubview:writeIcon];
        [textViewBgView addSubview:self.feedbackTextView];
        [textViewBgView addSubview:self.placeHolderLabel];
        [textViewBgView addSubview:self.wordNumLabel];
    }
    
    UIView *photoBgView = [[UIView alloc] initWithFrame:CGRectMake(0, feedbackView.maxY + KScaleWidth(10.0), self.width, KScaleWidth(211.0))];
    photoBgView.backgroundColor = kColorHEX(0xffffff);
    _photoBgView = photoBgView;
    [self addSubview:photoBgView];
    {
        CGFloat space = (photoBgView.width - KScaleWidth(112.0)*3)/4;
        for (int i = 0; i < 3; i ++) {
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(space + (KScaleWidth(112.0) + space)*i, KScaleWidth(73.0), KScaleWidth(112.0), KScaleWidth(112.0))];
            [imgView setCornerRadius:KScaleWidth(14.0)];
            [photoBgView addSubview:imgView];
            UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(imgView.maxX - KScaleWidth(22.0), imgView.y - KScaleWidth(8.0), KScaleWidth(28.0), KScaleWidth(28.0)) image:@"mine_img_delete_icon" selectImg:@"mine_img_delete_icon"];
            [deleteBtn addTarget:self action:@selector(imgDeleteAction:) forControlEvents:UIControlEventTouchUpInside];
            [photoBgView addSubview:deleteBtn];
            imgView.tag = 7000 + i;
            deleteBtn.tag = 32 + i;
            imgView.hidden = YES;
            deleteBtn.hidden = YES;
        }
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(20.0), KScaleWidth(17.0), photoBgView.width - KScaleWidth(17.0)*2, KScaleWidth(32.0)) font:KBoldFontSize(15.0) textColor:kColorHEX(0x333333)];
        titleLabel.text = @"请提供问题相关截图或照片";
        [photoBgView addSubview:titleLabel];
        
        UILabel *explainLabel = [[UILabel alloc] initWithFrame:CGRectMake(photoBgView.width - KScaleWidth(20.0) - KScaleWidth(80.0), KScaleWidth(18.0), KScaleWidth(80.0), KScaleWidth(30.0)) font:KFontSize(14.0) textColor:kColorHEX(0x999999) textAlignment:NSTextAlignmentRight];
        explainLabel.text = @"最多可上传3张";
        [photoBgView addSubview:explainLabel];
        [photoBgView addSubview:self.addImgBtn];
    }
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KBoldFontSize(17.0) frame:CGRectMake((self.width - KScaleWidth(320.0))/2, photoBgView.maxY + KScaleWidth(40.0), KScaleWidth(320.0), KScaleWidth(44.0)) title:@"提交" titleColor:kColorHEX(0x333333)];
    [confirmBtn setGradientLayerWithLocations:@[@(0), @(1.0)] colors:@[(__bridge id)kColorHEX(0xFFD800).CGColor, (__bridge id)kColorHEX(0xFFE44E).CGColor] startPoint:CGPointMake(0.5, 0.37) endPoint:CGPointMake(0.03, 0.37)];
    [confirmBtn setCornerRadius:confirmBtn.height/2];
    [confirmBtn addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:confirmBtn];
}

//确认
- (void)confirmAction:(UIButton *)button {
    self.submitBlock ? self.submitBlock(_feedbackTextView.text, self.imgSelectArr) : nil;
}

//删除图片
- (void)imgDeleteAction:(UIButton *)button {
    [self.imgSelectArr removeObjectAtIndex:button.tag - 32];
    UIImageView *imgView = [_photoBgView viewWithTag:7000 + button.tag - 32];
    XMWeakSelf;
    for (int i = 0; i < 3; i ++) {
        if ((button.tag - 32) < i) {
            UIImageView *imgView = [_photoBgView viewWithTag:7000 + i];
            UIButton *deleteBtn = [_photoBgView viewWithTag:32 + i];
            [UIView animateWithDuration:.3 animations:^{
                imgView.x = imgView.x - imgView.width - (weakSelf.photoBgView.width - imgView.width*3)/4;
                deleteBtn.x = imgView.maxX - KScaleWidth(22.0);
            } completion:^(BOOL finished) {
                
            }];
        }
    }
    [UIView animateWithDuration:.3 animations:^{
        imgView.alpha = 0;
        button.alpha = 0;
    } completion:^(BOOL finished) {
        imgView.hidden = YES;
        button.hidden = YES;
        imgView.alpha = 1;
        button.alpha = 1;
        [weakSelf setSelectImg];
    }];
}

- (void)addImgAction:(UIButton *)button {
    XMWeakSelf;
    UIAlertController *alertVC = [UIAlertController initwithTitle:@"选择图片" message:@"" titles:@[@"相机", @"相册"] alertStyle:UIAlertControllerStyleActionSheet itemSelect:^(NSInteger selectIndex) {
        if (selectIndex == 0) {
            [weakSelf selectImgFromCamera];
        }
        else {
            [weakSelf selectImgFromPhoto];
        }
    }];
    [self.viewController presentViewController:alertVC animated:YES completion:^{
        
    }];
}

- (void)registerFirst:(UITapGestureRecognizer *)tap {
    [self endEditing:YES];
}

- (void)textViewDidChange:(UITextView *)textView {
    _placeHolderLabel.hidden = (textView.text.length > 0);
    if (textView.text.length >= 240) {
        textView.text = [textView.text substringToIndex:240];
    }
    _wordNumLabel.text = [NSString stringWithFormat:@"%ld/240", textView.text.length];
}

//- (NSString *)getFeedbackContent {
//    return _feedbackTextView.text;
//}
//
//- (NSArray *)getSelectImgArr {
//    return self.getSelectImgArr;
//}

- (void)selectImgFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        pickerVC.delegate = self;
        [self.viewController presentViewController:pickerVC animated:YES completion:^{
            
        }];
    }
    else {
        [MBProgressHUD showError:@"无相机权限啊"];
    }
}

- (void)selectImgFromPhoto {
    [[XMImgSelect sharedInstance] selectImgFromLibraryOnVC:self.viewController];
    XMWeakSelf;
    [XMImgSelect sharedInstance].imgSelectBlock = ^(NSArray * _Nonnull imgArr) {
        [weakSelf.imgSelectArr addObjectsFromArray:imgArr];
        [weakSelf setSelectImg];
    };
//    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
//        UIImagePickerController *pickerVC = [[UIImagePickerController alloc] init];
//        pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        pickerVC.delegate = self;
//        [self.viewController presentViewController:pickerVC animated:YES completion:nil];
//    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *selectImg = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self.viewController dismissViewControllerAnimated:YES completion:nil];
    [self.imgSelectArr addObject:selectImg];
    [self setSelectImg];
}

- (void)setSelectImg {
    CGFloat space = (_photoBgView.width - KScaleWidth(112.0)*3)/4;
    for (int i = 0; i < 3; i ++) {
        UIImageView *imgView = [_photoBgView viewWithTag:7000 + i];
        UIButton *deleteBtn = [_photoBgView viewWithTag:32 + i];
        imgView.x = space + (KScaleWidth(112.0) + space)*i;
        deleteBtn.x = imgView.maxX - KScaleWidth(22.0);
        if (self.imgSelectArr.count > i) {
            imgView.hidden = NO;
            imgView.image = self.imgSelectArr[i];
            imgView.alpha = 1;
            
            deleteBtn.hidden = NO;
            deleteBtn.alpha = 1;
        }
        else {
            imgView.hidden = YES;
            deleteBtn.hidden = YES;
        }
    }
    XMWeakSelf;
    if (self.imgSelectArr.count >= 3) {
        _addImgBtn.hidden = YES;
    }
    else {
        _addImgBtn.hidden = NO;
        CGFloat space = (_photoBgView.width - KScaleWidth(112.0)*3)/4;
        [UIView animateWithDuration:.3 animations:^{
            weakSelf.addImgBtn.x = weakSelf.imgSelectArr.count*(space + KScaleWidth(112.0)) + space;
        }];
    }
}

#pragma mark - Init
- (UITextView *)feedbackTextView {
    if (!_feedbackTextView) {
        _feedbackTextView = [[UITextView alloc] initWithFrame:CGRectMake(KScaleWidth(37.0), KScaleWidth(14.0), self.width - KScaleWidth(20.0)*2 - KScaleWidth(37.0) - KScaleWidth(10.0), KScaleWidth(155.0) - KScaleWidth(14.0) - KScaleWidth(40.0))];
        _feedbackTextView.font = KFontSize(15.0);
        _feedbackTextView.backgroundColor = kColorHEX(0xF6F6F6);
        _feedbackTextView.delegate = self;
    }
    return _feedbackTextView;
}

- (UILabel *)placeHolderLabel {
    if (!_placeHolderLabel) {
        _placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(42.0), KScaleWidth(16.0), self.feedbackTextView.width, KScaleWidth(46.0)) font:KFontSize(15.0) textColor:kColorHEX(0x9b9b9b)];
        _placeHolderLabel.text = @"请输入15字以上描述，以便我们为您提供更好的帮助～";
        _placeHolderLabel.userInteractionEnabled = NO;
    }
    return _placeHolderLabel;
}

- (UILabel *)wordNumLabel {
    if (!_wordNumLabel) {
        _wordNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width - KScaleWidth(20.0)*2 - KScaleWidth(61.0), KScaleWidth(155.0) - KScaleWidth(14.0) - KScaleWidth(20.0), KScaleWidth(61.0), KScaleWidth(20.0)) font:KFontSize(14.0) textColor:kColorHEX(0x9b9b9b) textAlignment:NSTextAlignmentCenter];
        _wordNumLabel.text = @"0/240";
    }
    return _wordNumLabel;
}

- (UIButton *)addImgBtn {
    if (!_addImgBtn) {
        _addImgBtn = [UIButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(KScaleWidth(20.0), KScaleWidth(73.0), KScaleWidth(112.0), KScaleWidth(112.0)) image:@"mine_add_img_icon" selectImg:@"mine_add_img_icon"];
        [_addImgBtn addTarget:self action:@selector(addImgAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addImgBtn;
}

- (NSMutableArray *)imgSelectArr {
    if (!_imgSelectArr) {
        _imgSelectArr = [NSMutableArray array];
    }
    return _imgSelectArr;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
